package com.spzx.manager.utils;

import com.spzx.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * 封装树形菜单数据
 * <p>
 * Project: spzx-parent
 * Package: com.spzx.manager.utils
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2024/2/28 23:18
 */
public class MenuHelper {
    /**
     * 使用递归方法建菜单
     *
     * @param sysMenuList 查询出来的所有菜单
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        //封装最终的数据
        List<SysMenu> trees = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            //表示第一层
            if (sysMenu.getParentId().longValue() == 0) {
                trees.add(findChildren(sysMenu, sysMenuList));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param sysMenu   当前第一层菜单
     * @param treeNodes 所有菜单集合
     * @return
     */
    public static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> treeNodes) {
        sysMenu.setChildren(new ArrayList<SysMenu>());
        for (SysMenu it : treeNodes) {
            //如何id值和parent值一致则代表是id的下级
            if (sysMenu.getId().longValue() == it.getParentId().longValue()) {
                //if (sysMenu.getChildren() == null) {
                //    sysMenu.setChildren(new ArrayList<>());
                //}
                sysMenu.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return sysMenu;
    }
}
